
import datolib.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;


public class TcpSession {



    private DatoliteInstance instance;
	private TcpGateway gateway;
	
    public TcpSession() {
        this.gateway = null;
        this.instance = null;
    }
   
    public TcpSession(TcpGateway s, DatoliteInstance i) {
        this.gateway = s;
        this.instance = i;
        
    }
	
	
	/**
	* Continually run and listening for messages to execute until 
	* either DSC or EXT is sent
	*/
    public void run() {
        
  	  System.out.println(this.gateway.getRemoteAddress() + " connected, running application '" + this.instance.getApplicationID() + "'");

        try {
    
		
	    	while(true) {
		

			    XmlMessage msg = this.gateway.readNextMessage();
			  
                switch (msg.type()) {
			    	
			         case EXT:
			    	    System.out.println("connection with client is lost....");
				   	    this.gateway.close();
				   	    return;
				    case GUP:
					   UipTool.sendUIP(this.instance, this.gateway);
					   break;
				    case SAI:
					   this.startApplicationInstance();
					   break;
					case TEV:
						this.triggerEvent(msg.toTev());
						break;
				    default:
					   //this.gateway.unkownMessage(message.getText());
					   break;
			    
			    }
			    
			}
			    
		   
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }  
		
    }
      
    public void setControlProperty(String form, String control, String property) {
    	//this.write("\nIO IO IO IO IO IO IO");
    	System.out.println("CALL setControlProperty()");
    }
	
	/**
	* Call the  
	*/
	private void triggerEvent(TevMessage tev) {
    	
    	if (tev == null) {
    		return;
    	}
    	
    	if (this.instance == null) {
    		return;
    	}
    	
		this.instance.executeEvent(tev);	
		
    }
	
	private void startApplicationInstance() {

		if (!this.instance.buildInstance()) {
			this.gateway.ifl();
			return;
		}
		
	
		this.instance.initApplication(this.gateway);
		this.gateway.iss();
		
	}
	
}
